package com.itmuch.cms.shiro;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itmuch.cms.admin.domain.Admin;
import com.itmuch.cms.admin.service.IAdminService;
import com.itmuch.core.constants.SessionConstants;

public class ShiroDbRealm extends AuthorizingRealm {
    @Resource
    private IAdminService adminService;
    //    @Resource
    //    private IRoleService roleService;
    //    @Resource
    //    private IPermissionService permissionService;

    private static final Logger LOGGER = LoggerFactory.getLogger(ShiroDbRealm.class);

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //        String username = (String) principals.getPrimaryPrincipal();
        //        Admin admin = this.adminService.selectByUsername(username);
        //
        //        Role role = this.roleService.selectById(admin.getRoleId());
        //        SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
        //        // 如果是全站管理, 直接赋予所有权限
        //        if (role.getSuperFlag() == 1) {
        //            auth.addStringPermission("*");
        //        }
        //        // 不是超级管理员
        //        else {
        //            Set<String> permissions = this.permissionService.selectByRoleId(role.getId());
        //            if ((permissions != null) && !permissions.isEmpty()) {
        //                auth.addStringPermissions(permissions);
        //            }
        //        }
        //        return auth;

        return null;
    }

    /**
     * 认证回调函数,登录时调用.
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();

        Admin admin = this.adminService.selectByUsername(username);
        if (admin != null) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin.getUsername(), admin.getPassword(), ByteSource.Util.bytes(admin
                    .getSalt()), this.getName());
            this.setSession(SessionConstants.ADMIN_ID, admin.getId());
            this.setSession(SessionConstants.USERNAME, admin.getUsername());

            return info;
        } else {
            return null;
        }

    }

    /** 
     * 将一些数据放到ShiroSession中,以便于其它地方使用 
     * @see  比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 
     */
    private void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            LOGGER.debug("Session默认超时时间为[{}]毫秒.", session.getTimeout());
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }
}
